<%@page trimDirectiveWhitespaces="true"%>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>

<%
	System.out.println("in SAVE :");////////////////try////////////////

	//get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	//get value from tag
	String name =  request.getParameter("name");
	String surname = request.getParameter("surname");
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	String status = request.getParameter("status");
	String workgroup = request.getParameter("workgroup");
	String startDate = request.getParameter("startDate");
	String endDate = request.getParameter("endDate");
	int numRole = Integer.parseInt(request.getParameter("numRole"));
	String[] role = new String[numRole];
	int numDelete = Integer.parseInt(request.getParameter("numDelete"));
	String[] roleDelete = new String[numDelete];

	
	for(int i=0; i<numRole; i++) {
		role[i] = request.getParameter("role"+(i+1));
		
		System.out.println("role "+i+" : " + role[i]);////////////////try////////////////
	}
	
	for(int i=0; i<numDelete ; i++) {
		roleDelete[i] = request.getParameter("roleDelete"+(i+1));
		
		System.out.println("roleDelete "+i+" : " + roleDelete[i]);////////////////try////////////////
	}
	
	System.out.println("name :" + name);////////////////try////////////////
	System.out.println("surname :" + surname);////////////////try////////////////
	System.out.println("username :" + username);////////////////try////////////////
	System.out.println("password :" + password);////////////////try////////////////
	System.out.println("status :" + status);////////////////try////////////////
	System.out.println("workgroup :" + workgroup);////////////////try////////////////
	System.out.println("startDate :" + startDate);////////////////try////////////////
	System.out.println("endDate :" + endDate);////////////////try////////////////
	System.out.println("numRole :" + numRole);////////////////try////////////////
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps+ "&characterEncoding=tis620");
		
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	
	// find index in database
	String index = null;
	
	try {				
		ResultSet rs = connect.createStatement().executeQuery("SELECT `index`" +
					" FROM full_name"+
					" WHERE name_th='"+name+"' AND surname_th='"+surname+"' ");	
			
					
		while(rs.next()) {			
			index = rs.getString("index");
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	System.out.println("index :"+index);////////////try/////////////////////
	// IF dont have that name
		if(null ==index){
			out.print("Noname");
		}else{	
	
			/* insert data to database */
			String password_encrypt = null;
					
			String sql_account = "UPDATE  `account` SET `index`='"+index+"', `start_date`='"+startDate+"', `end_date`="+endDate
								+ " WHERE username='"+username+"'";
					
			String sql_user = "UPDATE `user` SET `status`='"+status+"', `workgroup_id`='"+workgroup+"'";
					
			if(!"null".equals(password)) {
				password_encrypt = PasswordHandler.encryptPassword(password);	
		
				sql_user = sql_user + ", `password`='"+password_encrypt+"' ";
			}
		
			sql_user = sql_user	+ " WHERE username='"+username+"'";
					
			System.out.println(sql_account);/////////////////////try///////////////////////////////
			System.out.println(sql_user);/////////////////////try///////////////////////////////
			
			try {		
					// update data into account 
					connect.createStatement().executeUpdate(sql_account);
					
					/* Log file */
					String log_account = "admin edit account";
					Log.writeAdminFile(log_account);
					Log.writeAdminFile(sql_account);
					
					// update data into user
					connect.createStatement().executeUpdate(sql_user);
					
					
					/* Log file */
					String log_user = "admin edit user";
					Log.writeAdminFile(log_user);
					Log.writeAdminFile(sql_user);
					
					String log_autho = "admin edit authorization ";
					Log.writeAdminFile(log_autho);
					
					// insert role into authorization
					for(int i=0 ;i<numRole; i++) {
						ResultSet rs = connect.createStatement().executeQuery("SELECT * "
																			+ " FROM authorization "
																			+ " WHERE role_id="+role[i]+" AND username='"+username+"'");
						
						if(rs.next()) { }
						else {
							String sql_autho = "INSERT INTO `authorization`(`role_id`, `username`) VALUES (" + role[i] + ", '" + username + "')";
							
							System.out.println(sql_autho);/////////////////////try///////////////////////////////
						
							connect.createStatement().executeUpdate(sql_autho);
									
							/* Log file */
							Log.writeAdminFile(sql_autho);
							
						}
						
					}
					
					// delete role 
					for(int i=0; i<numDelete; i++) {
						String sql_del_autho = "DELETE FROM `authorization` "
										+ " WHERE role_id="+roleDelete[i]+" AND username='"+username+"'";
						
						System.out.println(sql_del_autho);/////////////////////try///////////////////////////////
						
						connect.createStatement().executeUpdate(sql_del_autho);
								
						/* Log file */
						Log.writeAdminFile(sql_del_autho);
					}
					
					out.print("Success");
			} catch (SQLException e) {
				e.printStackTrace();
				
				out.print("Failed");
			}
		}
	
		connect.close();
%>